package edu.tongji.lockscreen;

import java.util.Calendar;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.provider.CallLog.Calls;
import android.provider.Telephony.Sms;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.fima.glowpadview.GlowPadView;
import com.fima.glowpadview.GlowPadView.OnTriggerListener;

import edu.tongji.lockscreen.BaiduWeatherInfo.EachCityWeatherInfo;

@SuppressLint("NewApi")
public class LockScreenActivity extends Activity implements OnGestureListener,
		OnTouchListener, OnTriggerListener {

	private static String TAG = "LockScreenActivity";

	private static boolean mLockStat = false;
	private RelativeLayout relativeLayout = null;
	private GestureDetector gestureDetector = null;
	private int bgImageIndex = -1;

	private static TextView currentLocation = null;
	private static TextView currentWeather = null;
	private static TextView currentTemperature = null;

	private List<Drawable> imageList = null;
	private GlowPadView glowPadView;

	private static String MISSCALL_SELECTION = "TYPE=3 AND NEW=1";
	private static String MISSSMS_SELECTION = "READ=0";

	public static Handler weatherHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			Log.i(TAG, msg.obj.toString());
			EachCityWeatherInfo cityWeatherInfo = ((BaiduWeatherInfo) msg.obj)
					.getCityWeatherInfoList().get(0);
			String currentCity = cityWeatherInfo.getCurrentCity();
			String weather = cityWeatherInfo.getDetailWeatherInfoList().get(0)
					.getWeather();
			String date = cityWeatherInfo.getDetailWeatherInfoList().get(0)
					.getDate();
			int index = date.indexOf("：");
			String temprature = date.substring(index + 1, date.length() - 1);
			currentLocation.setText(currentCity);
			currentWeather.setText(weather);
			currentTemperature.setText(temprature);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initLockScreenActivity();
		setContentView(R.layout.activity_lock_screen);
		initLockScreenBgImage();
		initLockScreenInfoPanel();
		initLockScreenGlowPadView();

		// Start Lock Screen Service
		startService(new Intent(LockScreenActivity.this,
				LockScreenService.class));
	}

	private void initLockScreenActivity() {
		// Remove Title Bar
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
	}

	@SuppressWarnings("deprecation")
	private void initLockScreenBgImage() {
		gestureDetector = new GestureDetector(this);
		relativeLayout = (RelativeLayout) findViewById(R.id.lockScreenBg);
		LockScreenImageLoader lockScreenImageLoader = LockScreenImageLoader
				.getInstance();
		imageList = lockScreenImageLoader.loadBackgroundImage(this);
		if (imageList.size() > 0) {
			relativeLayout.setBackground(imageList.get(0));
			bgImageIndex = 0;
		}
		relativeLayout.setOnTouchListener(this);
		relativeLayout.setLongClickable(true);
	}

	private void initLockScreenInfoPanel() {
		currentLocation = (TextView) findViewById(R.id.currentLocation);
		currentWeather = (TextView) findViewById(R.id.currentWeather);
		currentTemperature = (TextView) findViewById(R.id.currentTemperature);

		TextView currentTime = (TextView) findViewById(R.id.currentTime);
		TextView currentDate = (TextView) findViewById(R.id.currentDate);
		TextView currentWeek = (TextView) findViewById(R.id.currentWeek);
		TextView missCall = (TextView) findViewById(R.id.phoneNum);
		TextView missSMS = (TextView) findViewById(R.id.messageNum);

		long time = System.currentTimeMillis();
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(time);
		int hour = calendar.get(Calendar.HOUR);
		int minute = calendar.get(Calendar.MINUTE);
		String sHour = "";
		String sMinute = "";
		if (hour < 10)
			sHour = "0" + hour;
		else
			sHour = "" + hour;
		if (minute < 10)
			sMinute = "0" + minute;
		else
			sMinute = "" + minute;
		// Set Current Time
		currentTime.setText(sHour + ":" + sMinute);

		// Set Current Date
		int month = calendar.get(Calendar.MONTH) + 1;
		String sMonth = "" + month;
		currentDate.setText(sMonth + "月" + calendar.get(Calendar.DATE) + "日");

		// Set Current WeekDay
		String[] weekDays = { "周日", "周一", "周二", "周三", "周四", "周五", "周六" };
		int weekDay = calendar.get(Calendar.DAY_OF_WEEK) - 1;
		if (weekDay < 0)
			weekDay = 0;
		String sWeekDay = weekDays[weekDay];
		currentWeek.setText(sWeekDay);

		int iMissCall = 0;
		Cursor csr = this.getContentResolver().query(Calls.CONTENT_URI, null,
				MISSCALL_SELECTION, null, Calls.DEFAULT_SORT_ORDER);
		iMissCall = csr.getCount();
		csr.close();
		// Set Miss Call Num
		missCall.setText(String.valueOf(iMissCall));

		int iMissSMS = 0;
		csr = this.getContentResolver().query(Sms.CONTENT_URI, null,
				MISSSMS_SELECTION, null, Sms.DEFAULT_SORT_ORDER);
		iMissSMS = csr.getCount();
		csr.close();
		// Set Miss SMS Num
		missSMS.setText(String.valueOf(iMissSMS));

	}

	private void initLockScreenGlowPadView() {
		glowPadView = (GlowPadView) findViewById(R.id.glow_pad_view);
		glowPadView.setOnTriggerListener(this);
		glowPadView.setShowTargetsOnIdle(true);
	}

	public static boolean isLockStat() {
		return mLockStat;
	}

	public static void setLockStat(boolean mLockStat) {
		LockScreenActivity.mLockStat = mLockStat;
	}

	@Override
	public boolean onDown(MotionEvent e) {
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		return false;
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {

	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		if (bgImageIndex == -1)
			return false;
		if (e1.getX() - e2.getX() > 100) {
			bgImageIndex++;
			if (bgImageIndex >= imageList.size())
				bgImageIndex = 0;
		} else if (e1.getX() - e2.getX() < -100) {
			bgImageIndex--;
			if (bgImageIndex < 0)
				bgImageIndex = imageList.size() - 1;
		}
		relativeLayout.setBackground(imageList.get(bgImageIndex));
		return false;
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		return this.gestureDetector.onTouchEvent(event);
	}

	@Override
	public void onGrabbed(View v, int handle) {
	}

	@Override
	public void onReleased(View v, int handle) {
	}

	@Override
	public void onTrigger(View v, int target) {
		final int resId = glowPadView.getResourceIdForTarget(target);
		switch (resId) {
		case R.drawable.ic_item_sns:
			Toast.makeText(this, "SNS selected", Toast.LENGTH_SHORT).show();
			break;
		case R.drawable.ic_item_unlock:
			finish();
			break;
		case R.drawable.ic_item_website:
			Toast.makeText(this, "Website selected", Toast.LENGTH_SHORT).show();
			break;
		default:
		}
	}

	@Override
	public void onGrabbedStateChange(View v, int handle) {
	}

	@Override
	public void onFinishFinalAnimation() {
	}
}
